package com.stox.repository.file;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stox.manager.CountryManager;
import com.stox.model.Country;
import com.stox.model.Exchange;
import com.stox.repository.ExchangeRepository;

@Component
public class ExchangeFileRepository 
				extends AbstractFileRepository<Exchange, String> 
				implements ExchangeRepository, InitializingBean {

	@Autowired
	private CountryManager countryManager;
	
	private final Map<String, Map<String, Exchange>> cache = new HashMap<String, Map<String, Exchange>>();
	
	public void afterPropertiesSet() throws Exception {
		List<Country> countries = countryManager.findAll();
		for (Country country : countries) {
			final Map<String, Exchange> map = new HashMap<String, Exchange>();
			cache.put(country.getCode(), map);
			super.createPartition(country.getCode());
			iterate(new EntityIterator<Exchange>() {
				public boolean shouldContinue(Exchange exchange) {
					map.put(exchange.getCode(), exchange);
					return true;
				}
			}, country.getCode());
		}
	}

	public Exchange findOne(final String exchangeCode) {
		for(Map<String, Exchange> map : cache.values()){
			Exchange exchange = map.get(exchangeCode);
			if(null != exchange){
				return exchange;
			}
		}
		return null;	
	}

	public List<Exchange> findByCountryCode(String countryCode) {
		return new ArrayList<Exchange>(cache.get(countryCode).values());
	}

	@Override
	protected Exchange deserialize(String text, String countryCode) {
		return new Exchange(countryCode, text);
	}

	@Override
	protected String serialize(Exchange exchange) {
		return exchange.toString();
	}

	@Override
	protected String getFilePath(String countryCode) {
		return getFilebasePath() + File.separator + countryCode
				+ File.separator + "exchange.csv";
	}
	
	public Exchange save(Exchange exchange){
		if(null == findOne(exchange.getCode())){
			Map<String, Exchange> map = cache.get(exchange.getCountryCode());
			if(null == map){
				map = new HashMap<String, Exchange>();
				cache.put(exchange.getCountryCode(), map);
			}
			map.put(exchange.getCode(), exchange);
			return super.save(exchange, exchange.getCountryCode());
		}
		return exchange;
	}

}
